package com.yzycoc.qb78.service;

import cn.hutool.core.io.FileUtil;
import cn.hutool.http.HttpRequest;
import cn.hutool.http.HttpResponse;
import com.alibaba.fastjson.JSONObject;
import com.yzycoc.qb78.util.ExcelUtil;
import com.yzycoc.qb78.util.FileQb78Util;
import lombok.extern.slf4j.Slf4j;

import javax.swing.*;
import java.nio.charset.Charset;

/**
 * 创建时间： 2023/10/26
 *
 * @author yzy
 * @version 1.0
 **/
@Slf4j
public class Qb78Service {

    public static JSONObject config = null;

    public void run() {
        FileQb78Util.init();
        configInit();
        if (config == null) {
            log.error("读取配置失败，配置文件存在异常！");
        }
        Integer frequency = config.getInteger("frequency");
        int i = 1;
        while (true) {
            try {
                httpData(i);
                i++;
                Thread.sleep(frequency * 1000L);
            } catch (Exception e) {
                e.printStackTrace();
            }
        }
    }

    //GET /dev-api/chat/chat/list?pageNum=1&pageSize=10 HTTP/1.1
    //Host: super-admin-api.7pa.com
    //User-Agent: Mozilla/5.0 (Windows NT 10.0; Win64; x64; rv:109.0) Gecko/20100101 Firefox/118.0
    //Accept: application/json, text/plain, */*
    //Accept-Language: zh-CN,zh;q=0.8,zh-TW;q=0.7,zh-HK;q=0.5,en-US;q=0.3,en;q=0.2
    //Accept-Encoding: gzip, deflate, br
    //Authorization: Bearer eyJhbGciOiJIUzUxMiJ9.eyJsb2dpbl91c2VyX25hbWUiOiJjZXNoaXpoYW5naHVhMSIsImxvZ2luX3VzZXJfa2V5IjoiZmI0NmE4YmYtMmU5ZS00NzcxLWE1ZGYtMjI1M2Y3NTA0ZDM0In0.IDFJg0QiHkZiu52oSvHihPwRpKvVdbbvSbJu-eebNKL7K7f91FmmXBGYCIb44vWIajjigLPG_a7JE006pXchnw
    //Origin: https://super-admin.7pa.com
    //Connection: keep-alive
    //Referer: https://super-admin.7pa.com/
    //Sec-Fetch-Dest: empty
    //Sec-Fetch-Mode: cors
    //Sec-Fetch-Site: same-site
    //Pragma: no-cache
    //Cache-Control: no-cache
    private void httpData(Integer i) {
        try {
            String token = config.getString("token");
            HttpResponse execute = HttpRequest.get("https://super-admin-api.7pa.com/dev-api/chat/chat/list?pageNum=1&pageSize=50")
                    .header("Authorization", token)
                    .header("Referer", "https://super-admin.7pa.com/")
                    .header("User-Agent", "Mozilla/5.0 (Windows NT 10.0; Win64; x64; rv:109.0) Gecko/20100101 Firefox/118.0")
                    .header("Host", "super-admin-api.7pa.com")
                    .header("Origin", "https://super-admin.7pa.com/")
                    .header("Accept", "application/json, text/plain, */*")
                    .header("Accept-Language", "zh-CN,zh;q=0.8,zh-TW;q=0.7,zh-HK;q=0.5,en-US;q=0.3,en;q=0.2")
                    .header("Accept-Encoding", "gzip, deflate, br")
                    .execute();
            String body = execute.body();
            JSONObject bodyJSON = JSONObject.parseObject(body);
            if (bodyJSON.getInteger("code") == 401) {
                showLogin(i);
            } else if (bodyJSON.getInteger("code") == 200) {
                String run = new ExcelUtil().run(bodyJSON);
                log.info("成功\t爬取数据:{}次\t{}间隔：{}秒后继续爬取", i, run, config.getInteger("frequency"));
            } else {
                log.error("成功\t爬取数据:{}次 爬取数据异常:{}\t间隔：{}秒后继续爬取", i, body, config.getInteger("frequency"));
            }
        } catch (Exception e) {
            e.printStackTrace();
        }
    }


    private void showLogin(Integer i) {
        // 显示输入对话框
        log.error("失败\t爬取数据:{}次 登录失效! ", i);
        String input = JOptionPane.showInputDialog(null, "请输入新的token密钥 F12可以拿取", "登录token失效", JOptionPane.PLAIN_MESSAGE);
        // 判断用户是否点击了确认按钮并输入了内容
        if (input != null && !input.isEmpty()) {
            log.info("输入内容：" + input);
            config.put("token", input);
            String filePath = System.getProperty("user.dir") + "/config.json";
            FileUtil.writeString(config.toJSONString(), filePath, Charset.forName("UTF-8"));
            // 继续执行程序的逻辑写在这里
        } else {
            log.error("结束运行!");
            System.exit(0);
            // 可以在这里做相应的处理或者直接退出程序
        }
    }


    public void configInit() {
        try {
            String rootPath = System.getProperty("user.dir");
            String destinationPath = rootPath + "/config.json";
            String textConfig = FileUtil.readUtf8String(destinationPath);
            JSONObject configJSON = JSONObject.parseObject(textConfig);
            config = configJSON;
            log.info(config.toJSONString());
        } catch (Exception e) {
            e.printStackTrace();
            log.error("读取配置失败");
        }

    }

}
